//
//  RegHospitalListViewController.m
//  安好
//
//  Created by lianchuang on 14-12-10.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "RegHospitalListViewController.h"
//新的
#import "RegHospitalORdoctorCell.h"

#import "RegDoctorListViewController.h"

#import "RegexKitLite.h"
//从特需过来的
#import "TeXuRegViewController.h"
//分类挂号-》按医院过来
#import "ClassifyRegViewController.h"
//分类挂号-》按科室：选完科室过来
#import "WikiDepartmentViewController.h"
//
#import "ShaiXuanLeftCell.h"

#import "RightTableCell.h"


#define LeftWeight ([UIScreen mainScreen].bounds.size.width/2.0)
#define RGB(r, g, b)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]

#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

@interface RegHospitalListViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>
{
    FKSearchBar * illSeachBar;
}
/**
 *  电话数组
 */
@property(nonatomic,strong)NSArray * telArray;
/**
 *  左边的table
 */
@property(nonatomic,strong)UITableView * tableView;
/**
 * 左边的数据
 */
@property(nonatomic,strong)NSMutableArray * dataArray;
/**
 *  下拉加载页数
 */
@property (assign, nonatomic) NSInteger loadPage;

//---------------
/**
 *  筛选下拉BackView图贴两个tableView
 */
@property(nonatomic,strong)UIView * SelectBackView;

@property(nonatomic,strong)UIView * BackView;
@property(nonatomic,strong)UITableView * LeftTableView;

@property(nonatomic,strong)UITableView * RightTableView;
@property(nonatomic,strong)NSArray * RightDataArray;
/**
 *  省 name:id
 */
@property(nonatomic,strong)NSMutableDictionary * provinceDic;
/**
 * 等级 name:id
 */
@property(nonatomic,strong)NSMutableDictionary * dengjiDic;
/**
 *  等级name
 */
@property(nonatomic,strong)NSArray * dengjiNameArray;
/**
 *  省name
 */
@property(nonatomic,strong)NSMutableArray * provinceArray;

/**
 *  地区名字
 */
@property(nonatomic,copy)NSString * areaName;
/**
 *  等级名字
 */
@property(nonatomic,copy)NSString * leveName;
/**
 *  点击选中的左cell
 */
@property(nonatomic,strong)ShaiXuanLeftCell * leftSelectedCell;

/**
 *  网络请求参数
 */
@property(nonatomic,strong)NSMutableDictionary *AFNetParDic;
/**
 *  半透明的图片 -- 当点击升起pickerView的时候 这个也sheng起来
 *  筛选按钮触发后下拉视图下拉，这个半透明的背景视图也下来
 */
@property(nonatomic,strong)UIView * alphaView;

@property(nonatomic,assign)CGFloat filtHeight;

@end

@implementation RegHospitalListViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 取消输入框
    [illSeachBar.searchTextField resignFirstResponder];
    [self setEditing:NO animated:YES];
    
    [illSeachBar.searchTextField removeTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    [[AFHTTPRequestOperationManager manager].operationQueue cancelAllOperations];
    [self hiddenActionView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeNavBar];
    //初始化网络请求参数
    self.AFNetParDic = [NSMutableDictionary dictionaryWithCapacity:0];
    //初始化table的数据
    self.dataArray = [NSMutableArray arrayWithCapacity:0];
    //检索数组
    self.searchArray = [[NSMutableArray alloc]init];
    //
    self.filtHeight = 200;
    if (IPhone6Plus) {
        self.filtHeight = 240;
    }


    //创建底层的tableView
    [self makeTableView];
    //数据加载页数为1
    self.loadPage = 1;
    

    // 特需挂号
    if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[TeXuRegViewController class]]){

        [self AFNetRequestFOR_guahaohospital_List];
        [self.tableView addFooterWithTarget:self action:@selector(AFNetRequestFOR_guahaohospital_List)];
    }
    //分类挂号-按医院
    else if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[ClassifyRegViewController class]] ) {
        
        //创建搜索框
        [self markIllnessSearchBar];
        //创建检索tableView
        [self creatSearchTableView];
        
        //创建筛选按钮
        [self makeRightFilterItem];
        //创建下拉列表
        [self makeTopBackView];
        
        self.tableView.frame = CGRectMake(0, 43.5, kScreenWidth, kScreenHeight-iOS7TopMargin-43.5);
        [self AFNetRequestFOR_guahaohospital_List];
        [self.tableView addFooterWithTarget:self action:@selector(AFNetRequestFOR_guahaohospital_List)];
    }
    //分类挂号-按科室，选完科室过来
    else if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[WikiDepartmentViewController class]] ){
        
        [self AFNetRequestGetHospitalDepartment];
        [self.tableView addFooterWithTarget:self action:@selector(AFNetRequestGetHospitalDepartment)];
    }
    
}
#pragma - mark 搜索--searchBar
- (void)markIllnessSearchBar
{
    illSeachBar = [[FKSearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    illSeachBar.searchTextField.placeholder = @"医院";
    illSeachBar.searchTextField.delegate = self;
    illSeachBar.fkSearchRequestDelegate = self;
    [self.view addSubview:illSeachBar];
    [illSeachBar.searchTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
}

#pragma mark - 导航条设置
-(void)makeNavBar
{
    self.navigationItem.title = @"医院";
    //左按钮--返回
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}
/**
 *  创建-筛选-按钮
 */
-(void)makeRightFilterItem
{
    UIBarButtonItem *filterBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_筛选.png"] style:UIBarButtonItemStylePlain target:self action:@selector(filterBtnDown)];
    filterBtnItem.tag = 1000;
    filterBtnItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = filterBtnItem;
}
/**
 *  点击筛选按钮--触发下拉左右table，调用创建“完成”按钮
 */
-(void)filterBtnDown{
    [illSeachBar.searchTextField resignFirstResponder];
//
    if (self.provinceArray.count == 0) {
        //请求到省地区
        [self AFNetRequestForProvince];
    }else{
        [self ShowTheAreaAndLevelTableView];
    }
    
    
}
/**
 *  将地区/等级 下拉视图展示出来
 */
-(void)ShowTheAreaAndLevelTableView
{
    //筛选按钮--》完成按钮
    [self makeRightFilterFinishItem];
    //把下拉视图拉下来
    [self makeAlphaView];
    [self.view bringSubviewToFront:self.SelectBackView];
    [UIView animateWithDuration:0.25 animations:^{
        self.SelectBackView.frame = CGRectMake(0, 0, kScreenWidth, self.filtHeight);
        self.alphaView.alpha = 0.35;
        
    } completion:^(BOOL finished) {
        
    }];
}

/**
 *  创建“完成”按钮
 */
-(void)makeRightFilterFinishItem
{
    UIBarButtonItem *filterBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(filterFinishDown)];
    filterBtnItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = filterBtnItem;
    
}
#pragma mark - 完成按钮点击--按钮变为筛选--网络请求
/**
 *  点击"完成”按钮--》触发事件
 */
-(void)filterFinishDown{
    //完成--》筛选按钮
    
    [UIView animateWithDuration:0.25 animations:^{
        self.SelectBackView.frame = CGRectMake(0,-self.filtHeight, kScreenWidth, self.filtHeight);
        self.alphaView.alpha = 0;
    } completion:^(BOOL finished) {
        [self makeRightFilterItem];
        [self.alphaView removeFromSuperview];
    }];
    //修改网络参数
    self.parDic = @{@"provinceid":self.provinceDic[self.areaName],@"cityid":@"0",@"level":self.dengjiDic[self.leveName]};
    self.loadPage = 1;
    [self AFNetRequestFOR_guahaohospital_List];
    
    
}
#pragma mark - 筛选的连个table的低图和两个table的创建
-(void)makeTopBackView
{
    self.provinceDic = [NSMutableDictionary dictionaryWithCapacity:0];
    self.dengjiDic = [NSMutableDictionary dictionaryWithCapacity:0];
    self.provinceArray = [NSMutableArray arrayWithCapacity:0];
    
    self.dengjiNameArray = @[@"全部",@"三级特等",@"三级甲等",@"三级乙等",@"三级丙等",@"二级甲等",@"二级乙等",@"二级丙等",@"一级甲等",@"一级乙等",@"一级丙等",@"对外专科",@"其他"];
    NSArray * dengjiId = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12"];
    for (int i = 0; i < self.dengjiNameArray.count; i++) {
        [self.dengjiDic setValue:dengjiId[i] forKey:self.dengjiNameArray[i]];
    }
    
    //创建下拉底部view
    self.SelectBackView = [[UIView alloc] initWithFrame:CGRectMake(0, -self.filtHeight, kScreenWidth, self.filtHeight)];
    self.SelectBackView.backgroundColor = self.view.backgroundColor;
    [self.view addSubview:self.SelectBackView];
    
    //左table加在下拉view上
    self.LeftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LeftWeight ,self.filtHeight)style:UITableViewStylePlain];
    [self.SelectBackView addSubview:self.LeftTableView];
    self.LeftTableView.delegate = self;
    self.LeftTableView.dataSource = self;

    //隐藏横向和竖向的滑条
    self.LeftTableView.showsHorizontalScrollIndicator = NO;
    self.LeftTableView.showsVerticalScrollIndicator = NO;
    self.LeftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.LeftTableView.bounces = NO;
    UIView *botline = [[UIView alloc] initWithFrame:CGRectMake(self.LeftTableView.width-0.5, 80, 0.5, self.LeftTableView.height-80)];
    if (IPhone6Plus) {
        botline.frame = CGRectMake(self.LeftTableView.width-0.5,12+42+24, 0.5, self.LeftTableView.height-(12+42+42));
    }
    botline.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
    [self.LeftTableView addSubview:botline];
    UIView *topline = [[UIView alloc] initWithFrame:CGRectMake(self.LeftTableView.frame.size.width-0.5, 0, 0.5, 10)];
    if (IPhone6Plus) {
        topline.height = 12;
    }
    topline.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
    [self.LeftTableView addSubview:topline];
    
    //右边的table加在下拉view上
    self.RightTableView = [[UITableView alloc] initWithFrame:CGRectMake(LeftWeight, 0, kScreenWidth-LeftWeight, self.filtHeight)style:UITableViewStylePlain];
    [self.SelectBackView addSubview:self.RightTableView];
    self.RightTableView.delegate = self;
    self.RightTableView.dataSource = self;
    self.RightTableView.backgroundColor = RGB(238, 238, 238);
    //隐藏横向和竖向的滑条
    self.RightTableView.showsHorizontalScrollIndicator = NO;
    self.RightTableView.showsVerticalScrollIndicator = NO;
    self.RightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
//返回到上一个页面
-(void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin)style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView setSeparatorColor:RGB(221, 221, 221)];
    
}
/**
 *  检索tableView
 */
- (void)creatSearchTableView{
    self.searchTable = [[UITableView alloc]initWithFrame:CGRectMake(0,44, kScreenWidth, kScreenHeight - iOS7TopMargin - 44) style:UITableViewStyleGrouped];
    self.searchTable.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.searchTable.delegate = self;
    self.searchTable.dataSource = self;
    self.searchTable.showsHorizontalScrollIndicator = NO;
    self.searchTable.showsVerticalScrollIndicator = NO;
    [self.searchTable setSeparatorColor:RGB(221, 221, 221)];
    [self.view addSubview:self.searchTable];
    self.searchTable.hidden = YES;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.RightTableView == tableView || self.LeftTableView == tableView) {
        if (IPhone6Plus) {
            return 12;
        }else{
            return 10;
        }
    }else
    {
        return 0.01;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (self.RightTableView == tableView || self.LeftTableView == tableView) {
        if (IPhone6Plus) {
            return 6;
        }else{
            return 5;
        }
    }else
    {
        return 0.01;
    }
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.LeftTableView) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
        if (IPhone6Plus) {
            view.height = 12;
        }
        return view;
    }else if (tableView == self.RightTableView){
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
        if (IPhone6Plus) {
            view.height = 12;
        }
        view.backgroundColor = RGB(238, 238, 238);
        return view;
    }  else{
        return nil;
    }
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if ( tableView == self.LeftTableView) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 5)];
        if (IPhone6Plus) {
            view.height = 6;
        }
        return view;
    }else if(tableView == self.RightTableView){
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 5)];
        if (IPhone6Plus) {
            view.height = 6;
        }
        view.backgroundColor = RGB(238, 238, 238);
        return view;
    }else
    {
        return nil;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchTable) {
        return self.searchArray.count;
    }
    if (self.tableView == tableView) {
        return self.dataArray.count;
    }else if (self.LeftTableView == tableView){
    
        return 2;
    }else if (self.RightTableView == tableView){
        return self.RightDataArray.count;
    }else
    {
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tableView == tableView) {
        if (IPhone6Plus) {
            return 78;
        }else{
            return 65;
        }
    }else{
        if (IPhone6Plus) {
            return 42;
        }else{
            return 35;
        }
    }
}
#pragma mark  - 加载cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.searchTable){
        static NSString *reuseIdetify = @"SvTableViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdetify];
        }
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.backgroundColor = RGB(238, 238, 238);
        cell.textLabel.text = [self.searchArray objectAtIndex:indexPath.row];
        return cell;
    }

    if (self.tableView == tableView){
        
        RegHospitalORdoctorCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
        if (cell == nil) {
            if (IPhone6Plus) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"RegHospitalORdoctorCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"RegHospitalORdoctorCell" owner:self options:nil] firstObject];
            }
        }
        cell.userImageView.layer.masksToBounds = YES;
        cell.userImageView.layer.cornerRadius = 3;
        cell.bottomLineView.hidden = YES;
        cell.userLabel.width = kScreenWidth- cell.userLabel.left-15;
        cell.goodLabel.width = kScreenWidth-cell.goodLabel.left-15;
        
        
        //分类挂号-按科室，选完科室过来
        if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[WikiDepartmentViewController class]])
        {
            RegClassifyHosDepartModal * modal = self.dataArray[indexPath.row];
            cell.userLabel.text = modal.hospitalname;
            cell.goodLabel.text = modal.departmentname;
            cell.leaveLabel.text = modal.levelname;
            [cell.userImageView setImageWithURL:[NSURL URLWithString:modal.picurl] placeholderImage:[UIImage imageNamed:@"医院默认.png"]];
        }
        //分类挂号--按医院
        if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[ClassifyRegViewController class]]) {
            RegistrationHospitalModal * modal = self.dataArray[indexPath.row];
            cell.userLabel.text = modal.hospitalname;
            cell.goodLabel.text = modal.address;
            cell.leaveLabel.text = modal.levelname;
            [cell.userImageView setImageWithURL:[NSURL URLWithString:modal.picurl] placeholderImage:[UIImage imageNamed:@"医院默认.png"]];
            
        }
        //特需挂号
        if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[TeXuRegViewController class]])
        {
            RegistrationHospitalModal * modal = self.dataArray[indexPath.row];
            cell.userLabel.text = modal.hospitalname;
            cell.goodLabel.text = modal.address;
            cell.leaveLabel.text = modal.levelname;
            [cell.userImageView setImageWithURL:[NSURL URLWithString:modal.picurl] placeholderImage:[UIImage imageNamed:@"医院默认.png"]];
            cell.userImageView.clipsToBounds = YES;
            cell.userImageView.layer.cornerRadius = 3;
            
            if (modal.phone.length > 7) {
                [cell.hospitalPhoneImgView setImage:[UIImage imageNamed:@"phoneyes.png"]];
                [cell.phoneButton addTarget:self action:@selector(phoneButtonclicked:) forControlEvents:UIControlEventTouchUpInside];
                cell.phoneButton.tag = indexPath.row+100;
                
            }else
            {
                [cell.hospitalPhoneImgView setImage:[UIImage imageNamed:@"phoneno.png"]];
            }
            cell.hospitalPhoneImgView.right = kScreenWidth-15;
            cell.phoneButton.right = kScreenWidth - 15;
            cell.userLabel.left = cell.userImageView.right+10;
            cell.userLabel.width = cell.hospitalPhoneImgView.left-5-cell.userLabel.left;
            cell.goodLabel.left =cell.userImageView.right+10;;
            cell.goodLabel.width =cell.hospitalPhoneImgView.left-5-cell.userLabel.left;
            cell.userLabel.top = 10;
            cell.goodLabel.bottom = cell.contentView.height-12;
            
        }
        
        return cell;
    }
    else if (self.LeftTableView == tableView){
    //ShaiXuanLeftCell
        static NSString *indentify = @"leftCell";
        ShaiXuanLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:indentify];
        if (!cell) {
            if (IPhone6Plus) {
                 cell = [[[NSBundle mainBundle] loadNibNamed:@"ShaiXuanLeftCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"ShaiXuanLeftCell" owner:self options:nil] firstObject];
            }
        }
        cell.width = self.LeftTableView.width;
        cell.typeLabel.frame = CGRectMake(30,(cell.height-20)/2.0,30,20);
        
        cell.nameLabel.right = cell.width-30;
        cell.nameLabel.width = 60;
        cell.nameLabel.height = 20;
        cell.nameLabel.top = (cell.height - 20)/2.0;
        if (IPhone6Plus) {
             cell.typeLabel.frame = CGRectMake(40,(cell.height-20)/2.0,50,20);
            cell.nameLabel.frame = CGRectMake(cell.typeLabel.right+20, cell.typeLabel.top, cell.width - cell.typeLabel.right-20 - 40, 20);
        }
        
        if (indexPath.row == 0) {
            cell.typeLabel.text = @"地区";
            cell.nameLabel.text = self.areaName;
            cell.contentView.backgroundColor = RGB(238, 238, 238);
            self.leftSelectedCell = cell;
            
            
        }
        if (indexPath.row == 1) {
            cell.typeLabel.text = @"等级";
            cell.nameLabel.text = self.leveName;
            cell.rightlineView.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
        }
        cell.rightlineView.frame = CGRectMake(self.LeftTableView.width-0.5, 0, 0.5, cell.height);
        
        return cell;
    
    }
    else if (self.RightTableView == tableView){
        
        RightTableCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RightCell"];
        if (cell == nil) {
            if (IPhone6Plus) {
                 cell = [[[NSBundle mainBundle]loadNibNamed:@"RightTableCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle]loadNibNamed:@"RightTableCell" owner:self options:nil] firstObject];
            }
        }
        cell.contentView.backgroundColor = RGB(238, 238, 238);
        cell.nameLable.text = self.RightDataArray[indexPath.row];
        return cell;
        
    
    }
    else{
        return nil;
    }

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.searchTable) {
        
        illSeachBar.searchTextField.text = [self.searchArray objectAtIndex:indexPath.row];
        [self.view endEditing:YES];
        [self SearchString];
        
        return;
    }
    if (self.tableView == tableView) {
        RegDoctorListViewController * docList = [[RegDoctorListViewController alloc] init];
        //从分类挂号--按科室-》选好科室过来
        if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[WikiDepartmentViewController class]]) {
            RegClassifyHosDepartModal * modal = self.dataArray[indexPath.row];
            
            docList.regHosDepartDic = @{@"hospdeptid":modal.hospdeptid,@"hospitalid":modal.hospitalid};
            
        }
        //分类挂号-》按医院
        else if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[ClassifyRegViewController class]]) {
            
            RegistrationHospitalModal * modal = self.dataArray[indexPath.row];
            docList.regHosDepartDic = @{@"provinceid":self.parDic[@"provinceid"],@"cityid":self.parDic[@"cityid"],@"hospitalid":modal.hospitalid};
        }
        //从特需过来的
       else if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[TeXuRegViewController class]]){
           return;
            RegistrationHospitalModal * modal = self.dataArray[indexPath.row];
            docList.regHosDepartDic = @{@"provinceid":self.parDic[@"provinceid"],@"cityid":self.parDic[@"cityid"],@"hospitalid":modal.hospitalid};
        }
        
        [self.navigationController pushViewController:docList animated:YES];
    }
    else if (self.LeftTableView == tableView) {
        
        if (self.leftSelectedCell == nil) {
            self.leftSelectedCell = (ShaiXuanLeftCell*)[self.LeftTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        }
        
        
        
        MyNSLog("选中%d", indexPath.row);
        
        ShaiXuanLeftCell * cell = (ShaiXuanLeftCell*)[tableView cellForRowAtIndexPath:indexPath];
        cell.contentView.backgroundColor =RGB(240, 240, 240);
        cell.rightlineView.backgroundColor =RGB(240, 240, 240);
        
        self.leftSelectedCell.contentView.backgroundColor = self.LeftTableView.backgroundColor;
        self.leftSelectedCell.rightlineView.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
        self.leftSelectedCell = cell;
        
        if (indexPath.row == 0) {
            self.RightDataArray = self.provinceArray;
            [self.RightTableView reloadData];
        }
        if (indexPath.row == 1) {
            self.RightDataArray = self.dengjiNameArray;
            [self.RightTableView reloadData];
        }
        
        
        
    }
    else if (self.RightTableView == tableView) {
        NSString * nameString = self.RightDataArray[indexPath.row];
        self.leftSelectedCell.nameLabel.text = nameString;
        
        if ([self.leftSelectedCell.typeLabel.text isEqualToString:@"地区"]) {
            self.areaName = nameString;
        }
        if ([self.leftSelectedCell.typeLabel.text isEqualToString:@"等级"]) {
            self.leveName = nameString;
        }
        
    }

}
//打电话
-(void)phoneButtonclicked:(UIButton *)button
{
    RegistrationHospitalModal * modal = self.dataArray[button.tag-100];
    MyNSLog("电话是 %@", modal.phone);
    if ([modal.phone length] > 0) {
        NSString *regexString  = @"(\\d{11})|(\\d{3}-\\d{3}-\\d{4})|(\\d{3,4}-\\d{7,8}|(\\d{7,8}))";
        NSArray * matchArray = [modal.phone componentsMatchedByRegex:regexString];
        //切割第一，是在保证第一个有区号的情况下
        NSArray * subArray = [matchArray[0] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-"]];
        NSString * quhao = subArray[0];
        MyNSLog("%@ 区号 %@",modal.hospitalname ,quhao);
        MyNSLog("%@", matchArray);
        NSMutableArray * endArray = [NSMutableArray arrayWithCapacity:0];
        for (NSString * string in matchArray) {
            NSRange range = [string rangeOfString:@"-"];
            if (range.location == NSNotFound) {
                NSMutableString * subStr = [NSMutableString stringWithCapacity:0];
                [subStr appendString:quhao];
                [subStr appendString:@"-"];
                [subStr appendString:string];
                [endArray addObject:subStr];
            }else
            {
                [endArray addObject:string];

            }
        }
        MyNSLog("%@", endArray);
        
        self.telArray = endArray;
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        for ( int i=0; i<[self.telArray count]; i++) {
            [actionSheet addButtonWithTitle:[self.telArray objectAtIndex:i]];
        }
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        
        [actionSheet addButtonWithTitle:@"取消"];
        actionSheet.cancelButtonIndex=actionSheet.numberOfButtons-1;
        [actionSheet showInView:[[UIApplication sharedApplication].delegate window]];
    }
    
    
    
    
    
}
//打电话代理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == [actionSheet cancelButtonIndex]) {
        return;
    }
    else {
        //NSLog(@"打电话");
        NSString *number = [self.telArray objectAtIndex:buttonIndex];
        NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@",number];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
    }
}
//
#pragma mark - AFNet - 特需挂号 / 分类挂号-医院
-(void)AFNetRequestFOR_guahaohospital_List{
    
    [self showActionView];
    NSMutableDictionary * afparDic = [NSMutableDictionary dictionaryWithCapacity:0];
    [afparDic setDictionary:self.parDic];
    //如果点击搜索
    if (self.isSearch == YES) {
        //关键字不为空
        if ([illSeachBar.searchTextField.text length] != 0) {
            //把参数中添加 关键字参数
            [afparDic setValue:self.searchhospital forKey:@"keyword"];
        }else{
            self.parDic = @{@"provinceid":@"0",@"cityid":@"0",@"level":@"0"};
             [afparDic setDictionary:self.parDic];
            self.isSearch = NO;
        }
    }
    [afparDic setValue:[NSString stringWithFormat:@"%ld",self.loadPage] forKey:@"page"];
    [afparDic setValue:kPlatform forKey:@"platform"];
    [afparDic setValue:kVersion forKey:@"version"];
    //特许挂号--需要添加一个字段isremarks
    if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[TeXuRegViewController class]]) {
        [afparDic setValue:@"1" forKey:@"isremarks"];
    }
    
    
    NSString *postURL = [NSString stringWithFormat:@"%@guahao/hospital/",kBaseURL];
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:afparDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"])//没有数据
        {
            if (self.loadPage == 1 ){
                if (self.isSearch == YES && [responseObject[@"data"] count]==0 ) {
                    [self.dataArray removeAllObjects];
                    [self.tableView reloadData];
                }else{
                    if ([responseObject[@"data"] count]==0) {
                        [self.dataArray removeAllObjects];
                        [self.tableView reloadData];
                    }
                }
                [self shouLabel:@"暂无内容"];
            }
            [self.tableView footerEndRefreshing];
        }
        else//有数据
        {
            [self hiddenLabel];
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            //如果这个网络请求是正在搜索过来的
            if (self.isSearch == YES)
            {
                //判断数组是否为空--》需要清空数据--重新获取
                if ([self.dataArray count] != 0){
                    [self.dataArray removeAllObjects];
                }
            }
            //筛选的时候需要将loadPage==1
            if (self.loadPage == 1) {
                [self.dataArray removeAllObjects];
            }
            //如果有数据
            if (jsonDictArr != nil) {
                self.loadPage++;//搜索页++
                //有数据开始加载
                self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
                //往数组中加载数据
                for (NSDictionary * dic in jsonDictArr) {
                    RegistrationHospitalModal * modal = [[RegistrationHospitalModal alloc] initWithDic:dic];
                    [self.dataArray addObject:modal];
                }
                [self.tableView reloadData];
            }else{
                if (self.loadPage > 1) {
                     MyNSLog("下拉无数据");
                }
            
            }
            [self.tableView footerEndRefreshing];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        [self hiddenActionView];
        [self.tableView footerEndRefreshing];
    }];

}

#pragma mark - AFNet - 从按科室--选完科室后过来- 挂号过来
-(void)AFNetRequestGetHospitalDepartment{
    
    [self showActionView];
    NSString *postURL = [NSString stringWithFormat:@"%@guahao/HospitalDepartment",kBaseURL];
    NSDictionary * parameters =@{@"platform": kPlatform,@"version":kVersion,@"page":[NSString stringWithFormat:@"%ld",self.loadPage],@"departmentid":self.parDic[@"departmentid"]};
    
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            if (self.loadPage == 1 && responseObject[@"data"]== nil ) {
                [self shouLabel:@"暂无内容"];
            }
            [self.tableView footerEndRefreshing];
        }else
        {
            [self hiddenLabel];
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            
            NSArray * hospitalArray = responseObject[@"data"];
            
            if (hospitalArray != nil ) {
                self.loadPage ++;
                
                for (NSMutableDictionary * dic in hospitalArray) {
                    
                    RegClassifyHosDepartModal * modal = [[RegClassifyHosDepartModal alloc] initWithDic:dic];
                    [self.dataArray addObject:modal];
                    
                }
                [self.tableView reloadData];
            }else
            {
                if (self.loadPage > 1) {
                    MyNSLog("下拉无数据");
                }
            }
            [self.tableView footerEndRefreshing];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        [self hiddenActionView];
        [self.tableView footerEndRefreshing];
    }];
    
}

#pragma mark - 这个请求某一个所有省
//传“0”就是获取到所有的省，点击省的时候，把该省的provinceid传过来请求该省下面的所有市
-(void)AFNetRequestForProvince
{
    [self showActionView];
    //筛选按钮
    UIBarButtonItem * shaixuanBtn = (UIBarButtonItem *)[self.view viewWithTag:1000];
    shaixuanBtn.enabled = NO;
    
    NSString *postURL = [NSString stringWithFormat:@"%@guahao/area/",kBaseURL];
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"provinceid":@"0"};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        [self hiddenActionView];
        shaixuanBtn.enabled = YES;
        
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:@"筛选地区无数据"];
        }
        else
        {
            //第一个是全部
            [self.provinceDic setValue:@"0" forKey:@"全部"];
            [self.provinceArray addObject:@"全部"];
            for (NSDictionary * dic in responseObject[@"data"]) {
                AreaModal * modal = [[AreaModal alloc] initWithDic:dic];
                [self.provinceDic setValue:modal.provinceid forKey:modal.name];
                [self.provinceArray addObject:modal.name];
            }
            self.RightDataArray = self.provinceArray;
            self.areaName = self.provinceArray[0];
            self.leveName = self.dengjiNameArray[0];
            [self.LeftTableView reloadData];
            [self.RightTableView reloadData];
            //展示下拉
            [self ShowTheAreaAndLevelTableView];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        [self hiddenActionView];
        shaixuanBtn.enabled = YES;
    }];
}
#pragma - mark FKSearchDelegate
/**
 *  FKSearch的delegate
 */
- (void)VoiceConversion
{
    [illSeachBar.searchTextField resignFirstResponder];
    [self starVoice];
}
- (void)voice:(NSString *)voice
{
    illSeachBar.searchTextField.text = voice;
   //
    self.isSearch = YES;
    self.loadPage = 1;
    self.searchhospital = voice;
    [self AFNetRequestFOR_guahaohospital_List];
}
- (void)SearchString
{
    [illSeachBar.searchTextField resignFirstResponder];
   
    self.isSearch = YES;
    self.loadPage = 1;
    self.searchhospital = illSeachBar.searchTextField.text;
    [self AFNetRequestFOR_guahaohospital_List];
}

#pragma mark - 创建半透明的view
-(void)makeAlphaView
{
    self.alphaView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    self.alphaView.backgroundColor = [UIColor blackColor];
    self.alphaView.alpha = 0;
    [self.view addSubview:self.alphaView];
    //给这个半透明的View添加一个手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alphaViewTapClicked:)];
    [self.alphaView addGestureRecognizer:tap];
}
-(void)alphaViewTapClicked:(UITapGestureRecognizer*)tap{
    
    [UIView animateWithDuration:0.25 animations:^{
        self.SelectBackView.frame = CGRectMake(0,-self.filtHeight, kScreenWidth, self.filtHeight);
        self.alphaView.alpha = 0;
    } completion:^(BOOL finished) {
        [self makeRightFilterItem];
        [self.alphaView removeFromSuperview];
    }];

}
#pragma mark - 检索的textField
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (!self.tableView.hidden) {
        self.tableView.hidden = YES;
        self.searchTable.hidden = NO;
    }
    return YES;
    
}
//结束编辑的时候--把table显示出来，检索searchTable隐藏
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (!self.searchTable.hidden) {
        self.tableView.hidden = NO;
        self.searchTable.hidden = YES;
    }
}
/**
 *  textField上面的字符串一有变化就网络请求检索
 *
 *  @param textField
 */
- (void)textFieldEditChanged:(UITextField *)textField
{
    if (!self.searchTable.hidden) {
        
        [self loadsearchData:textField.text];
    }
    MyNSLog("textField text : %@", [textField text]);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (!self.searchTable.hidden) {
        
        [self SearchString];
    }
    return YES;
}
/**
 *  加载检索请求
 *
 *  @param text 输入的字符
 */
-(void)loadsearchData:(NSString*)text{
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setValue:text forKey:@"q"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [[manager operationQueue] cancelAllOperations];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,AUTO_HOSPITAL] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        [self.searchArray removeAllObjects];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            MyNSLog("%@", jsonDictArr);
            for (NSDictionary *objc in jsonDictArr) {
                [self.searchArray addObject:objc];
            }
        }
        [self.searchTable reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.searchTable reloadData];
        
    }];
    
}

@end
